/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.dressingsocial.service;

import com.dressingsocial.model.Role;
import com.dressingsocial.model.User;
import com.dressingsocial.repository.UserRepository;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author hayate
 */
@Service
@Transactional
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserRepository userRepository;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection pc) {
        String email = (String) pc.fromRealm(getName()).iterator().next();
        User user = userRepository.findByEmail(email);
        if (user != null) {
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            Set<String> roleNameSet = new HashSet<String>();
            List<Role> roles = user.getRoles();
            if (!roles.isEmpty()) {
                for (Role role : roles) {
                    roleNameSet.add(role.getName());
                }
            }
            info.setRoles(roleNameSet);
            for (Role role : roles) {
                info.addStringPermissions(role.allPermissionsNames());
            }
            return info;
        }
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken at) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) at;
        User user = userRepository.findByEmail(token.getUsername());
        if (user != null) {
            return new SimpleAuthenticationInfo(user.getEmail(), user.getPassword(), getName());
        }

        return null;
    }

}
